const plugin = requirePlugin("logisticsPlugin");
export default {
	data() {
		return {
			statusArr: [{
				title: '全部',
				key: '0'
			}, {
				title: '待付款',
				key: '1'
			}, {
				title: '待发货',
				key: '2'
			}, {
				title: '待收货',
				key: '3'
			}, {
				title: '已收货',
				key: '4'
			}, {
				title: '已退款',
				key: '6'
			}],
			statusSel: '0',
			orderList: []
		}
	},
	async onLoad(options) {
		console.log("orders index onLoad: ", options);
		this.statusSel = options.type || '0';
	},
	async onShow() {
		const self = this;
		await this.onPageInit();
		this.nowTimeInterval = setInterval(() => {
			for (let i = 0; i < self.orderList.length; i++) {
				const tmpOrder = self.orderList[i];
				if (tmpOrder.status === '1' && tmpOrder.invalid_time) {
					self.orderList[i].invalid_time_str = self.getInvalidTime(tmpOrder.invalid_time);
				}
			}
		}, 1000)
	},
	onHide() {
		clearInterval(this.nowTimeInterval);
	},
	async onPullDownRefresh() {
		await this.onPageInit();
		uni.stopPullDownRefresh();
	},
	methods: {
		// 初始化数据
		async onPageInit() {
			const listRes = await this.$uniCloudCallFunction({
				name: 'xxf-order',
				action: 'getOrderList',
				data: {
					uid: this.$store.state.login.uid,
					status: this.statusSel
				}
			});
			console.log("listRes: ", listRes);
			if (listRes) {
				this.orderList = listRes.list || [];
			} else {
				this.orderList = [];
			}
		},
		async switchStatus(e) {
			this.statusSel = e.key || '0';
			await this.onPageInit();
		},
		getInvalidTime(endTime) {
			const now = new Date();
			const end = new Date(endTime);
			const diff = end - now; // 计算剩余时间
			if (diff > 0) {
				// 计算时间
				const seconds = Math.floor(diff / 1000);
				const minutes = Math.floor(seconds / 60);
				const hours = Math.floor(minutes / 60);
				const days = Math.floor(hours / 24);

				let ss = seconds % 60;
				ss = ss <= 9 ? `0${ss}` : `${ss}`;
				let mm = minutes % 60;
				mm = mm <= 9 ? `0${mm}` : `${mm}`;
				let hh = hours % 60;
				hh = hh <= 9 ? `0${hh}` : `${hh}`;

				return `${mm}:${ss}`;
			} else {
				return '';
			}
		},
		async cancelOrder(e) {
			if (await this.$utils.showModal(this, {
					title: '取消订单',
					content: `您确认取消该订单？\n(No：${e._id})\n若需退款将原路退回。`,
				})) {
				const cancelRes = await this.$uniCloudCallFunction({
					name: 'xxf-order',
					action: "cancelOrder",
					data: {
						uid: this.$store.state.login.uid,
						orderId: e._id
					}
				});
				console.log("cancelRes: ", cancelRes);
				if (cancelRes) {
					await this.$utils.showToast(this, {
						message: '订单已取消！',
						mode: 1
					});
					await this.onPageInit();
				}
			}
		},
		async payOrder(e) {
			const payRes = await this.$uniCloudCallFunction({
				name: 'xxf-order',
				action: "payOrder",
				data: {
					uid: this.$store.state.login.uid,
					openId: this.$store.state.login.openId,
					orderId: e._id
				}
			});
			console.log("payRes: ", payRes);
			const self = this;
			if (payRes) {
				uni.requestPayment({
					timeStamp: payRes.timeStamp,
					nonceStr: payRes.nonceStr,
					package: payRes.package, //统一下单接口返回的 prepay_id 格式如：prepay_id=***
					signType: payRes.signType || 'MD5',
					paySign: payRes.paySign, //签名
					success(res) {
						console.log("支付成功", res)
						self.$utils.showToast(self, {
							message: '支付成功！',
							mode: 1
						});
					},
					fail(res) {
						console.log("支付失败", res)
						self.$utils.showToast(self, {
							message: '支付失败！',
							mode: 2
						});
					},
					complete(res) {
						console.log("支付完成", res);
						try {
							self.$uniCloudCallFunction({
								name: 'xxf-order',
								action: "checkOrderStatus",
								data: {
									uid: self.$store.state.login.uid,
									openId: self.$store.state.login.openId,
									orderId: e._id
								}
							});
						} catch (e) {
							console.log("complete checkOrderStatus", e);
						}
						setTimeout(() => {
							self.onPageInit();
						}, 2500);
					}
				})
			}
		},
		async getDelivery(e) {
			if (e.waybill_num) {
				let detailList = [];
				for (let i = 0; i < e.product_list.length; i++) {
					detailList.push({
						goods_name: e.product_list[i].productInfo.name,
						goods_img_url: e.product_list[i].productInfo.thumb,
					})
				}
				const getRes = await this.$uniCloudCallFunction({
					name: 'xxf-order',
					action: "getWaybillToken",
					data: {
						uid: this.$store.state.login.uid,
						open_id: this.$store.state.login.openId,
						order_id: e._id,
						receiver_phone: e.receive_info.phone,
						waybill_num: e.waybill_num,
						goods_info: {
							detail_list: detailList
						},
						trans_id: e.notify_info.transactionId,
					}
				});
				console.log("getRes: ", getRes);
				const waybillToken = getRes.waybill_token || "";
				if (waybillToken) {
					//必须用预览才能测试这个功能，无法在工具端模拟
					plugin.openWaybillTracking({
						waybillToken: waybillToken
					});
				} else {
					if (await this.$utils.showModal(this, {
							title: '查询失败',
							content: `订单信息未更新，可复制物流编号自行查询！\n(物流编号：${e.waybill_num})`,
							confirmTxt: '复制',
						})) {
						// 设置剪贴板内容
						uni.setClipboardData({
							data: e.waybill_num,
							success: () => {
								console.log('copyOrderNo success : ', e.waybill_num);
							}
						});
					}
				}
			}
		},
		async onReceived(e) {
			if (await this.$utils.showModal(this, {
					title: '收货',
					content: `请您务必确认已经收到货了？\n(No：${e._id})`,
					confirmTxt: '已收货',
				})) {
				console.log("已经收到货了！");
				const receivedRes = await this.$uniCloudCallFunction({
					name: 'xxf-order',
					action: "receivedOrder",
					data: {
						order_id: e._id,
					}
				});
				console.log("receivedRes: ", receivedRes);
				if (receivedRes) {
					this.$utils.showToast(this, {
						message: '收货成功！',
						mode: 2
					});
					await this.onPageInit();
				}
			}
		},
		async toService(e) {
			if (await this.$utils.showModal(this, {
					mode: 1,
					title: '售后',
					content: `您可以联系客服为您处理？\n(No：${e._id})`,
					cancelTxt: '取消',
					confirmTxt: '复制单号并联系',
				})) {
				console.log("复制单号并联系！");
				// 设置剪贴板内容
				uni.setClipboardData({
					data: e._id,
					success: () => {
						console.log('copyOrderNo success : ', e._id);
					}
				});
			}
		},
		toOrderDetail(e) {
			uni.navigateTo({
				url: `/pages/minePack/orderDetail/index?id=${e._id}`,
			})
		},
		toProductDetail(e) {
			uni.navigateTo({
				url: `/pages/homePack/proDetail/index?id=${e.productId}`,
			})
		}
	},
}